//
// Created by zhupi on 2024/9/29.
//

#include "tree_base_widget.h"
#include <QStandardItemModel>
#include "tree_base_model.h"


#include "project_manager_menu.h"
TreeBaseWidget::TreeBaseWidget(QWidget *parent) : QTreeView(parent) {
    // 设置右键菜单策略为自定义
    setContextMenuPolicy(Qt::CustomContextMenu);
    connect(this, &TreeBaseWidget::customContextMenuRequested, this, &TreeBaseWidget::CustomContextMenu);
}

void TreeBaseWidget::DeteteItem(const QModelIndex &index)
{

    // 删除节点的逻辑
    TreeModel *model = qobject_cast<TreeModel *>(this->model());
    if (model == nullptr) {
        return;
    }
    TreeNode* node = static_cast<TreeNode *>(index.internalPointer());
    if (node == nullptr) {
        return;
    }
    int id = node->data_.id_;
    model->MoveItem(id);
    emit DeleteItemSg(id);
}

void TreeBaseWidget::CustomContextMenu(const QPoint &point)
{
    QModelIndex index = indexAt(point);
    if (!index.isValid()) {
        return; // 如果点击的位置不在任何一个节点上，不弹出菜单
    }
    // TreeNode* node = static_cast<TreeNode*>(index.internalPointer());
    TreeNode* node = static_cast<TreeNode*>(index.internalPointer());
    if (node == nullptr) {
        return;
    }
    if (node->isDisabled_) {
        return;
    }
    // 获取当前点击的项的信息
    QString itemName = index.data().toString();
    qDebug() << "Right-clicked on:" << itemName;

    // 创建右键菜单
    QMenu contextMenu(this);
    ProjectManagerMenu::GetIns().GetAutoMenu(10, DataType::ProjectManager, contextMenu);
//    QAction *action1 = contextMenu.addAction("Action 1");
//    QAction *action2 = contextMenu.addAction("Action 2");
//    QAction *action3 = contextMenu.addAction("Delete");

    // 显示菜单并处理选择的动作
    QAction *selectedAction = contextMenu.exec(viewport()->mapToGlobal(point));
//    if (selectedAction == action1) {
//        qDebug() << "Action 1 selected for item:" << itemName;
//    } else if (selectedAction == action2) {
//        qDebug() << "Action 2 selected for item:" << itemName;
//    } else if (selectedAction == action3) {
//        qDebug() << "Delete action selected for item:" << itemName;
//        // 在这里添加删除节点的逻辑
//        DeteteItem(index);
//    }
}
